package com.bdqn.t330.ch12.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class T330Filter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init 初始化");
    }

    //注意拦截路径是在web.xml中配置的
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("sysUser") == null) {
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index");
        } else {
            //执行url目标地址
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("doFilter......................");
        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy 销毁");
    }
}
